package com.ecmap.hongyun.commons.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Random;

public class StringUtils extends org.apache.commons.lang.StringUtils{
	
	/**
	 * 获取固定长度的随机数字字符串，不足位数在前面补0
	 * @param strLength 字符串长度
	 * @return
	 */
	public  static String getFixLenthString(int strLength) {  
	      
	    Random rm = new Random();  
	    // 返回固定的长度的随机数  
	    String rmResult = String.valueOf( rm.nextInt((int)Math.pow(10,strLength*2)) ); 
	    int len = rmResult.length() - strLength;
	    if( len > 0 ){
	    	//大于0，表示长度过长，从左到右截取
	    	rmResult = rmResult.substring(rmResult.length() - strLength, rmResult.length());
	    }else if( len < 0 ){
	    	//小于0，表示长度不足，在前面补0
	    	String prefix = "" ;
	    	for( int i = 0 ; i > len ; i-- ){
	    		prefix += "0";
	    	}
	    	rmResult = prefix+ rmResult;
	    }
	    
	    return rmResult;   
	} 
	
    /** 
     * 文本文件转换为指定编码的字符串 
     * 
     * @param file         文本文件 
     * @param encoding 编码类型 UTF-8,GBK
     * @return 转换后的字符串 
     * @throws IOException 
     */ 
    public static String file2String(File file, String encoding) { 
            InputStreamReader reader = null; 
            StringWriter writer = new StringWriter(); 
            try { 
                    if (encoding != null && !"".equals(encoding.trim())) { 
                            reader = new InputStreamReader(new FileInputStream(file), encoding); 
                    } else { 
                            reader = new InputStreamReader(new FileInputStream(file)); 
                    } 
                    //将输入流写入输出流 
                    char[] buffer = new char[1024]; 
                    int n = 0; 
                    while (-1 != (n = reader.read(buffer))) { 
                            writer.write(buffer, 0, n); 
                    } 
            } catch (Exception e) { 
                    e.printStackTrace(); 
                    return null; 
            } finally { 
                    if (reader != null) 
                            try { 
                                    reader.close(); 
                            } catch (IOException e) { 
                                    e.printStackTrace(); 
                            } 
            } 
            //返回转换结果 
            return writer.toString(); 
    }
    
    /** 
     * 将字符串写入指定文件(当指定的父路径中文件夹不存在时，会最大限度去创建，以保证保存成功！) 
     * 
     * @param res            原字符串 
     * @param filePath 文件路径 
     * @return 成功标记 
     */ 
    public static boolean string2File(String res, String filePath) { 
            boolean flag = true; 
            BufferedReader bufferedReader = null; 
            BufferedWriter bufferedWriter = null; 
            try { 
                    File distFile = new File(filePath); 
                    if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs(); 
                    bufferedReader = new BufferedReader(new StringReader(res)); 
                    bufferedWriter = new BufferedWriter(new FileWriter(distFile)); 
                    char buf[] = new char[1024];         //字符缓冲区 
                    int len; 
                    while ((len = bufferedReader.read(buf)) != -1) { 
                            bufferedWriter.write(buf, 0, len); 
                    } 
                    bufferedWriter.flush(); 
                    bufferedReader.close(); 
                    bufferedWriter.close(); 
            } catch (IOException e) { 
                    e.printStackTrace(); 
                    flag = false; 
                    return flag; 
            } finally { 
                    if (bufferedReader != null) { 
                            try { 
                                    bufferedReader.close(); 
                            } catch (IOException e) { 
                                    e.printStackTrace(); 
                            } 
                    } 
            } 
            return flag; 
    }
    
	 /**
     * 图片转化成base64字符串  
     * @param imgPath 图片文件
     * @return 返回Base64编码过的字节数组字符串  
     */
    public static String image2String(String imgPath){
    	//将图片文件转化为字节数组字符串，并对其进行Base64编码处理  
        InputStream in = null;  
        byte[] data = null;  
        //读取图片字节数组  
        try{  
            in = new FileInputStream(imgPath);          
            data = new byte[in.available()];  
            in.read(data);  
           
        } catch (IOException e){  
          
        }finally{
			try {
				if( in != null)in.close();
			} catch (IOException e) {
			}  
        }
        //对字节数组Base64编码  
        //返回Base64编码过的字节数组字符串  
        return new String(org.apache.commons.codec.binary.Base64.encodeBase64(data));
    }  
      
    /**
     * base64字符串转化成图片  
     * @param imgString Base64编码过的字节数组字符串  
     * @param imgPath 保存图片的路径
     * @return 
     */
    public static boolean string2Image(String imgString,String imgPath) {  
    	//对字节数组字符串进行Base64解码并生成图片  
        if (imgString == null) //图像数据为空  
            return false;  
        
        OutputStream out = null ;
        try{  
            //Base64解码  
            byte[] b = org.apache.commons.codec.binary.Base64.decodeBase64(imgString.getBytes());  
            
            out = new FileOutputStream(imgPath);      
            out.write(b);  
            out.flush();  
            return true;  
        } catch (Exception e){  
            return false;  
        }finally{
			try {
				if( out != null)out.close();
			} catch (IOException e) {
			} 
        }
    }  
    
	 /**
	  * 获取字符串MD5
	  * 
	  * @author DANIEL DENG
	  * @createTime 2012-2-8
	  * @lastModify DANIEL DENG 2012-2-8
	  * @param source
	  * @return
	  */
	public static String getMD5(String source) {

		String s = null;
		// 用来将字节转换成 16 进制表示的字符
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] b = source.getBytes("UTF-8");
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			md.update(b);
			byte tmp[] = md.digest();
			char str[] = new char[16 * 2];
			int k = 0;
			for (int i = 0; i < 16; i++) {

				byte byte0 = tmp[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];

				str[k++] = hexDigits[byte0 & 0xf];
			}
			s = new String(str);

		} catch (Exception e) {
			//e.printStackTrace();
		}
		return s;
	}
    
	/**
	 * 加盐MD5（source.hashCode() + source+source.length() + source.hashCode()）
	 * @param source 目标字符串
	 * @return 加盐MD5字符串
	 */
	public static String getMD5WithSalt(String source){
		return getMD5( source.hashCode() + source +source.length()+ source.hashCode() );
	}
	
	public static void main(String[] args) {
		/*
		String fileStrUtf = file2String( new File("E:/111.txt"), "UTF-8");
		System.out.println(fileStrUtf);
		System.out.println( fileStrUtf.length());
		
		String fileStrGBK = file2String( new File("E:/111.txt"), "GBK");
		System.out.println(fileStrGBK);
		System.out.println( fileStrGBK.length());
		
		String fileStr = file2String( new File("E:/111.txt"), "");
		System.out.println(fileStr);
		System.out.println( fileStr.length());
		
		string2File(fileStrUtf, "E:/utf.txt");
		string2File(fileStrGBK, "E:/gbk.txt");
		string2File(fileStr, "E:/000.txt");
		
		String fileStr = image2String("E:/111.jpg");
		System.out.println(fileStr);
		System.out.println( fileStr.length());
		
		string2Image(fileStr,  "E:/000.jpg");
		 */
		//2f87f0009be659b209508650f4ce4a9a
		System.out.println(getMD5("123456"));
	}
	
}
